package com.zmjmall.demo.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zmjmall.demo.api.UserService;
import com.zmjmall.demo.dto.UserDTO;
import com.zmjmall.demo.enums.ResultEnum;
import com.zmjmall.demo.exception.MallAuthorizeException;
import com.zmjmall.demo.model.User;
import com.zmjmall.demo.util.FileImgUtil;
import com.zmjmall.demo.utils.QiniuUtil;
import com.zmjmall.demo.utils.ResultVOUtil;
import com.zmjmall.demo.util.UUIDUtil;
import com.zmjmall.demo.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 用户信息控制层
 * @author zmj
 * @version 2018/7/3
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Reference
    private UserService userService;
    @Autowired
    private QiniuUtil qiniuUtil;
    /**
     * 获取个人信息
     * @param userId
     * @return
     */
    @GetMapping
    @ResponseBody
    public ResultVO findByPhoe(String userId,User user){
        user.setId(userId);
        return  ResultVOUtil.success(userService.getUser(user));
    }

    /**
     * 修改个人资料
     * @param userId
     * @param userDTO
     * @return
     */
    @PostMapping
    @ResponseBody
    public ResultVO create(String userId,@Valid UserDTO userDTO) {
        User user = new User();
        user.setId(userId);
        BeanUtils.copyProperties(userDTO,user);
        if(userService.updateUserInfo(user)) {
            return  ResultVOUtil.success(ResultEnum.SUCCESS);
        }
        throw new MallAuthorizeException(ResultEnum.OPERATE_ERROR);
    }

    /**
     * 头像上传 上传到七牛云
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public ResultVO uploadHeadImg(@RequestParam("file") MultipartFile multipartFile,String userId,User user) throws IOException {
        FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();
        if(!FileImgUtil.isImage(inputStream)) {
            throw new MallAuthorizeException(ResultEnum.HEAD_NOT_IMG);
        }
        String uuid = UUIDUtil.uuid();
        String path = qiniuUtil.put64image(multipartFile.getBytes(),uuid);
        user.setHead(path);
        user.setId(userId);
        //删除之前的
        User user1 = userService.getUser(user);
        qiniuUtil.delete(user1.getHead());

        userService.updateUserInfo(user);

        return ResultVOUtil.success(path);
    }

}
